package cn.com.yinhex.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

public class IPUtil {
	
	private static  boolean isLicitIp(String ip)
	{
		if (ip==null||ip.length()==0) 
		{
			return false;
		}
		String regex = "^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(ip);
		if (!m.find()) 
		{
			return false;
		}
		return true;
	}
	
	/*
	 * ȡ����ʵIP������������ת��4��IP
	 */
	public static String getRealIP(HttpServletRequest request)
	{
		String ip;
		ip = request.getHeader("X-Forwarded-For");
		if (ip==null||ip.length()==0)
		{
			ip= request.getRemoteAddr();
		}
		else
		{
			ip = ip.split(", ")[0].trim();
			if ("127.0.0.1".equals(ip) || !isLicitIp(ip))
			{
				ip= request.getRemoteAddr();
			}
		}
		
		
		return ip;
	}
}
